<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="采购合同号" prop="purchaseContractNum">
              <el-input v-model="queryParams.purchaseContractNum" placeholder="请输入采购合同号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <supplier-select v-model:supplierId="queryParams.supplierId" />
            </el-form-item>
            <el-form-item label="运输路段" prop="transportSection">
              <el-select v-model="queryParams.transportSection" placeholder="请选择运输路段" clearable
                @keyup.enter="handleQuery">
                <el-option v-for="item in transport_section" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="采购发票号" prop="purchaseInvoiceNum">
              <el-input v-model="queryParams.purchaseInvoiceNum" placeholder="请输入采购发票号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发票入账日期" prop="recordDate">
              <el-date-picker clearable v-model="queryParams.recordDate" type="daterange" value-format="YYYY-MM-DD"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['finance:purchaseInvoice:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['finance:purchaseInvoice:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['finance:purchaseInvoice:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['finance:purchaseInvoice:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border height="400" :data="purchaseInvoiceList"
        @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.purchaseInvoiceList" border>
              <el-table-column prop="purchaseInvoiceNum" label="采购发票号" align="center" />
              <el-table-column prop="voucherNum" label="相关凭证号" align="center" />
              <el-table-column prop="recordDate" label="发票入账日期" align="center">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="originalTotalAmount" label="原币价税合计" align="center">
                <template #default="scope">
                  {{ Number(scope.row.originalTotalAmount || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="originalAmount" label="原币无税金额" align="center">
                <template #default="scope">
                  {{ Number(scope.row.originalTotalAmount || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="originalTaxAmount" label="原币税额" align="center">
                <template #default="scope">
                  {{ Number(scope.row.originalTotalAmount || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="币种" align="center" prop="currency">
                <template #default="scope">
                  <dict-tag :options="bas_currency" :value="scope.row.currency" />
                </template>
              </el-table-column>
              <el-table-column prop="exchangeRate" label="汇率" align="center">
                <template #default="scope">
                  {{ Number(scope.row.exchangeRate || 0).toFixed(6) }}
                </template>
              </el-table-column>
              <el-table-column prop="localTotalAmount" label="本币价税合计" align="center">
                <template #default="scope">
                  {{ Number(scope.row.localTotalAmount || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="localAmount" label="本币无税金额" align="center">
                <template #default="scope">
                  {{ Number(scope.row.localAmount || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="localTaxAmount" label="本币税额" align="center">
                <template #default="scope">
                  {{ Number(scope.row.localTaxAmount || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" align="center"/>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="采购合同号" align="center" prop="purchaseContractNum" />
        <el-table-column label="项目名称" align="center" prop="projectName" width="120" />
        <el-table-column label="运输路段" align="center" prop="transportSection">
          <template #default="scope">
            <dict-tag :options="transport_section" :value="scope.row.transportSection" />
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="币种" align="center" prop="currency">
          <template #default="scope">
            <dict-tag :options="bas_currency" :value="scope.row.currency" />
          </template>
        </el-table-column>
        <el-table-column label="本币价税合计" align="center" prop="localTotalAmount" :formatter="formatAmount" width="120" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button icon="view" type="success" size="small" @click="handleView(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="PurchaseInvoice" lang="ts">
import { listPurchaseInvoice, getPurchaseInvoice, delPurchaseInvoice, addPurchaseInvoice, updatePurchaseInvoice } from '@/api/finance/purchaseInvoice';
import { PurchaseInvoiceVO, PurchaseInvoiceQuery, PurchaseInvoiceForm } from '@/api/finance/purchaseInvoice/types';
import { exportPurchaseInvoiceExcel } from '@/utils/exportToExcel';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { transport_section, bas_currency } = toRefs<any>(proxy?.useDict('transport_section', 'bas_currency'));

const purchaseInvoiceList = ref<PurchaseInvoiceVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const purchaseInvoiceFormRef = ref<ElFormInstance>();


const initFormData: PurchaseInvoiceForm = {
  id: undefined,
  purchaseContractId: undefined,
  remark: undefined,
}
const data = reactive<PageData<PurchaseInvoiceForm, PurchaseInvoiceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    purchaseContractId: undefined,
    params: {
    }
  },
  rules: {
    purchaseContractId: [
      { required: true, message: "采购合同id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form } = toRefs(data);

/** 查询采购发票列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {
    ...queryParams.value.params,
    recordDateBegin: queryParams.value.recordDate?.[0] || '',
    recordDateEnd: queryParams.value.recordDate?.[1] || '',
  };
  delete queryParams.value.recordDate;
  const res = await listPurchaseInvoice(queryParams.value);
  purchaseInvoiceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
const reset = () => {
  form.value = { ...initFormData };
  purchaseInvoiceFormRef.value?.resetFields();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: PurchaseInvoiceVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$router.push({
    path: `/finance/invoiceEdit/index`,
    query: {
      type: 'add',
      contractType: 'purchase',
      from: proxy.$route.fullPath
    }
  })
}

const handleView = (row?: PurchaseInvoiceVO) => {
  proxy.$router.push({
    path: `/finance/invoiceEdit/index`,
    query: {
      id: row.id,
      type: 'view',
      contractType: 'purchase',
      from: proxy.$route.fullPath
    }
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PurchaseInvoiceVO) => {
  const _id = row?.id || ids.value[0]
  proxy.$router.push({
    path: `/finance/invoiceEdit/index`,
    query: {
      id: _id,
      type: 'update',
      contractType: 'purchase',
      from: proxy.$route.fullPath
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (row?: PurchaseInvoiceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除采购发票编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delPurchaseInvoice(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  exportPurchaseInvoiceExcel(purchaseInvoiceList.value)
}
const formatAmount = (_row: any, _column: any, value: any) => {
  if (value === null || value === undefined || value === '') return '-';
  return Number(value).toFixed(2);
};
onMounted(() => {
  getList();
});
</script>
